/*
 * JEditScheduleDialog.java
 *
 * Created on 22 maj 2008, 21:06
 */

package schoolmanagement.dialogs;

import java.util.List;
import javax.swing.table.DefaultTableModel;
import schoolmanagement.controller.DBAccess;
import schoolmanagement.controller.ErrorLogger;
import schoolmanagement.entity.SmClass;
import schoolmanagement.entity.SmDay;
import schoolmanagement.entity.SmRing;
import schoolmanagement.entity.SmSchedule;

/**
 *
 * @author  deely
 */
public class JEditScheduleDialog extends javax.swing.JDialog {
    
    private SmClass m_class;
    
    /** Creates new form JEditScheduleDialog */
    public JEditScheduleDialog(java.awt.Frame parent, boolean modal, SmClass cls) {
        super(parent, modal);
        initComponents();
        m_class = cls;
        loadRings();
    }

    private void editSelectedLesson() {
        SmDay day;
        SmRing ring;
        SmSchedule lesson;
        
        if( jTblDays.getSelectedRowCount() != 1 ) return;
        if( jTblSchedule.getSelectedRowCount() != 1 ) return;
        
        day = (SmDay) jTblDays.getModel().getValueAt(jTblDays.getSelectedRow(), 0 );
        ring = (SmRing) jTblSchedule.getModel().getValueAt( jTblSchedule.getSelectedRow(), 0 );
        lesson = (SmSchedule) jTblSchedule.getModel().getValueAt( jTblSchedule.getSelectedRow(), 1 );
        
        JAddLessonDialog nl = new JAddLessonDialog(null, true, m_class, day, ring, lesson );
        nl.setLocationRelativeTo(null);
        nl.setVisible(true);
        
        SmSchedule res = nl.getResult();
        
        if( res != null )
        {/*
            ( m_lesson, m_teacher, m_classroom, (SmSubject)jcbSubjects.getSelectedItem() );
            if( !DBAccess.GetInstance().updateSchedule(res, ) )
            {
                ErrorLogger.getInstance().error("Could not update schedule!");
            }*/
        }
        
        reloadSchedule();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTblDays = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTblSchedule = new javax.swing.JTable();
        jbtnAdd = new javax.swing.JButton();
        jbtnDelete = new javax.swing.JButton();
        jbtnCancel = new javax.swing.JButton();

        setName("Form"); // NOI18N
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Edycja planu")); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTblDays.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"Poniedzialek"},
                {"Wtorek"},
                {"Sroda"},
                {"Czwartek"},
                {"Piatek"}
            },
            new String [] {
                "Dzien tygodnia"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTblDays.setName("jTblDays"); // NOI18N
        jTblDays.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTblDaysMouseClicked(evt);
            }
        });
        jTblDays.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
                jTblDaysCaretPositionChanged(evt);
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
            }
        });
        jTblDays.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jTblDaysPropertyChange(evt);
            }
        });
        jTblDays.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTblDaysKeyReleased(evt);
            }
        });
        jTblDays.addVetoableChangeListener(new java.beans.VetoableChangeListener() {
            public void vetoableChange(java.beans.PropertyChangeEvent evt)throws java.beans.PropertyVetoException {
                jTblDaysVetoableChange(evt);
            }
        });
        jScrollPane1.setViewportView(jTblDays);

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTblSchedule.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Lekcja", "Przedmiot", "Nauczyciel", "Sala"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTblSchedule.setName("jTblSchedule"); // NOI18N
        jTblSchedule.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTblScheduleMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jTblSchedule);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(schoolmanagement.SchoolmanagementApp.class).getContext().getResourceMap(JEditScheduleDialog.class);
        jbtnAdd.setText(resourceMap.getString("jbtnAdd.text")); // NOI18N
        jbtnAdd.setName("jbtnAdd"); // NOI18N
        jbtnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAddActionPerformed(evt);
            }
        });

        jbtnDelete.setText(resourceMap.getString("jbtnDelete.text")); // NOI18N
        jbtnDelete.setName("jbtnDelete"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 452, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jbtnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtnAdd)
                    .addComponent(jbtnDelete)))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE)
        );

        jbtnCancel.setText("Zamknij"); // NOI18N
        jbtnCancel.setName("jbtnCancel"); // NOI18N
        jbtnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jbtnCancel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnCancel)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbtnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCancelActionPerformed
        setVisible(false);        // TODO add your handling code here:
    }//GEN-LAST:event_jbtnCancelActionPerformed

    private void jbtnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAddActionPerformed
        editSelectedLesson();
    }//GEN-LAST:event_jbtnAddActionPerformed

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        List<SmDay> list = DBAccess.GetInstance().getAllDays();
        DefaultTableModel tm = (DefaultTableModel) jTblDays.getModel();
        while( tm.getRowCount() > 0 ) tm.removeRow(0);
        
        for( SmDay day : list )
        {
            tm.addRow(new Object[] { day } );
        }
    }//GEN-LAST:event_formComponentShown

    private void jTblDaysCaretPositionChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_jTblDaysCaretPositionChanged
        
    }//GEN-LAST:event_jTblDaysCaretPositionChanged

    private void jTblDaysPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jTblDaysPropertyChange
        
    }//GEN-LAST:event_jTblDaysPropertyChange

    public void reloadSchedule()
    {
        if( jTblDays.getSelectedRowCount() != 1 ) return;
        int row = jTblDays.getSelectedRow();
        SmDay day = (SmDay) jTblDays.getValueAt( row, 0 );
        if( day != null )
        {
            reloadScheduleFor( day );
        }
    }
    
    private void jTblDaysVetoableChange(java.beans.PropertyChangeEvent evt)throws java.beans.PropertyVetoException {//GEN-FIRST:event_jTblDaysVetoableChange

    }//GEN-LAST:event_jTblDaysVetoableChange

    private void jTblDaysMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTblDaysMouseClicked
        reloadSchedule();
    }//GEN-LAST:event_jTblDaysMouseClicked

    private void jTblDaysKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTblDaysKeyReleased
        reloadSchedule();
    }//GEN-LAST:event_jTblDaysKeyReleased

    private void jTblScheduleMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTblScheduleMouseClicked
        if( evt.getClickCount() != 2 ) return;
        editSelectedLesson();
    }//GEN-LAST:event_jTblScheduleMouseClicked
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                JEditScheduleDialog dialog = new JEditScheduleDialog(new javax.swing.JFrame(), true, null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTblDays;
    private javax.swing.JTable jTblSchedule;
    private javax.swing.JButton jbtnAdd;
    private javax.swing.JButton jbtnCancel;
    private javax.swing.JButton jbtnDelete;
    // End of variables declaration//GEN-END:variables

    private void loadRings() {
        List<SmRing> list = DBAccess.GetInstance().getRings();

        DefaultTableModel tm = (DefaultTableModel) jTblSchedule.getModel();
        while( tm.getRowCount() > 0 ) tm.removeRow( 0 );
        
        for( SmRing ring : list )
        {
            tm.addRow( new Object[] { ring, null, null, null } );
        }
    }

    private void reloadScheduleFor(SmDay day) {
        
        loadRings();
        DefaultTableModel tm = (DefaultTableModel) jTblSchedule.getModel();
        
        List<SmSchedule> list = DBAccess.GetInstance().getSchedule(day, m_class);
        if( list == null ) return;
        
        for( int i=0; i<tm.getRowCount(); ++i )
        {
            SmRing ring = (SmRing) tm.getValueAt(i, 0);
            for( SmSchedule lesson : list )
            {
                if( lesson.getSchRngId() == ring )
                {
                    tm.setValueAt(lesson, i, 1);
                    tm.setValueAt(lesson.getSchTchPerId(), i, 2);
                    tm.setValueAt(lesson.getSchClrId(), i, 3);
                }
            }
        }
    }
    
}
